package com.crm.service.service;

import com.crm.common.mapper.ServiceMapper;
import com.crm.global.exception.CrmException;
import com.crm.global.exception.ExceptionEnum;
import com.crm.id.increment.IdWorker;
import com.crm.mybatis.separation.Read;
import com.crm.mybatis.separation.Write;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

@Service
public class TblServiceImpl {

    @Autowired
    private ServiceMapper serviceMapper;

    @Write
    public void saveOrUpdate(com.crm.common.pojo.Service tblService) {
        if (tblService == null) {
            throw new CrmException(ExceptionEnum.PARAM_IS_NULL);
        }
        if (tblService.getId() == null) {
            tblService.setId(new IdWorker().nextId());
            serviceMapper.insertSelective(tblService);
        } else {
            serviceMapper.updateByPrimaryKey(tblService);
        }
    }

    @Read
    public PageInfo<com.crm.common.pojo.Service> findAll(int page,int size,com.crm.common.pojo.Service tblService) {
        PageHelper.startPage(page,size);
        tblService = tblService != null ? tblService : new com.crm.common.pojo.Service();

        Example example = new Example(com.crm.common.pojo.Service.class);
        Example.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(tblService.getCustomerName())) {
            criteria.andLike("customerName","%" + tblService.getCustomerName() + "%");
        } else if (StringUtils.isNotBlank(tblService.getTitle())) {
            criteria.andLike("title","%" + tblService.getTitle() + "%");
        } else if (StringUtils.isNotBlank(tblService.getType())) {
            criteria.andEqualTo("type",tblService.getType());
        } else if (StringUtils.isNotBlank(tblService.getStatus())) {
            criteria.andEqualTo("status",tblService.getStatus());
        }

        return new PageInfo<>(serviceMapper.selectByExample(example));
    }

    @Read
    public com.crm.common.pojo.Service selectById(Long id) {
        if (id == null) {
            throw new CrmException(ExceptionEnum.PARAM_IS_NULL);
        }
        return serviceMapper.selectByPrimaryKey(id);
    }



    @Write
    public void deleteById(Long id) {
        if (id == null) {
            throw new CrmException(ExceptionEnum.PARAM_IS_NULL);
        }
        serviceMapper.deleteByPrimaryKey(id);
    }
}
